//
//  DeadTimeViewController.m
//  ProjectB
//
//  Created by lanou on 16/5/5.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "DeadTimeViewController.h"
#import "YYCoreDataHandler.h"
#import "ClockView.h"
#import "PortraitsViewController.h"
#import "AppDelegate.h"
#import <SVProgressHUD.h>
#import "RecordTableViewController.h"

@interface DeadTimeViewController ()<UIPickerViewDelegate, UIPickerViewDataSource>

@property (weak, nonatomic) IBOutlet UIImageView *deadImageVIew;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *deadViews;
@property (weak, nonatomic) IBOutlet UIButton *lifeTimeButton;
@property (weak, nonatomic) IBOutlet UILabel *aLabel;
@property (weak, nonatomic) IBOutlet UIButton *shareButton;
@property (weak, nonatomic) IBOutlet UIStackView *stackViewOne;
@property (weak, nonatomic) IBOutlet UIStackView *stackViewTwo;
@property (nonatomic, strong) UIBarButtonItem *headItem;
@property (nonatomic, strong) UIBarButtonItem *wishItem;
@property (nonatomic, strong) UIBarButtonItem *menuItem;
@property (nonatomic, strong) ClockView *clockView;
@property (strong, nonatomic) UILabel *bLabel;
@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, strong) UIView *pickerView;
@property (nonatomic, strong) UIPickerView *picker;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, strong) UIButton *chooseT;
@property (nonatomic, strong) UIButton *chooseF;

@end

@implementation DeadTimeViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"black"] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    
    User *user = [[YYCoreDataHandler sharedCoreDataHandler] selectObjectByKey:[[NSUserDefaults standardUserDefaults] objectForKey:@"currentUser"]].firstObject;
    self.age = [user getAge];
    [self.picker reloadComponent:0];
    [self.picker selectRow:99 inComponent:0 animated:NO];
    
    NSNumber *age = user.maxAge;
    if (age.integerValue < self.age) {
        [self startAnimation:NO];
        if (age.integerValue < 0) {
            [SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight];
            [SVProgressHUD showInfoWithStatus:@"请重新预测你的年龄"];
            [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.extendedLayoutIncludesOpaqueBars = YES;
//    self.navigationController.navigationBar.translucent = YES;
    
    _headItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"headW"] style:UIBarButtonItemStylePlain target:self action:@selector(goHead)];
    _wishItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"wishW"] style:UIBarButtonItemStylePlain target:self action:@selector(goWish)];
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:_wishItem, _headItem, nil];
    
    for (UILabel *l in _deadViews) {
        l.layer.borderColor = [UIColor lightGrayColor].CGColor;
        l.layer.borderWidth = 1;
    }
    
    self.lifeTimeButton.layer.cornerRadius = 15;
    self.lifeTimeButton.layer.borderWidth = 1;
    self.lifeTimeButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.lifeTimeButton.tag = 3333;
    
    [self showData];
}

- (void)showData {
    NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:@"currentUser"];
    User *user = [[YYCoreDataHandler sharedCoreDataHandler] selectObjectByKey:username].firstObject;
    
    NSArray<NSString *> *deadTime = [user getDeadTime];
    NSMutableArray *deadStrs = [[NSMutableArray alloc] init];
    [deadStrs addObject:[NSString stringWithFormat:@"吃%@顿饭", [deadTime objectAtIndex:0]]];
    [deadStrs addObject:[NSString stringWithFormat:@"睡%@个觉", [deadTime objectAtIndex:1]]];
    [deadStrs addObject:[NSString stringWithFormat:@"过%@个周末", [deadTime objectAtIndex:2]]];
    [deadStrs addObject:[NSString stringWithFormat:@"过%@个情人节", [deadTime objectAtIndex:3]]];
    
    for (int i = 0; i < 4; i++) {
        [[self.deadViews objectAtIndex:i] setValue:[deadStrs objectAtIndex:i] forKey:@"text"];
    }
    
    [self.lifeTimeButton setTitle:@"生之时" forState:UIControlStateNormal];
    self.timeLabel.text = [NSString stringWithFormat:@"这是你一生中的%@点%@分", [deadTime objectAtIndex:4], [deadTime objectAtIndex:5]];
    
    if (self.clockView) {
        self.clockView.hour = [deadTime objectAtIndex:4].integerValue;
        self.clockView.minute = [deadTime objectAtIndex:5].integerValue;
    } else {
        _clockView = [[ClockView alloc] initWithFrame:self.deadImageVIew.bounds hour:[deadTime objectAtIndex:4].integerValue minute:[deadTime objectAtIndex:5].integerValue second:-1 autoRun:NO];
        [_clockView changeColor];
        [self.deadImageVIew addSubview:_clockView];
    }
    
}

- (void)goHead {
    PortraitsViewController *PortraitsVC = [[PortraitsViewController alloc] init];
    [self.navigationController pushViewController:PortraitsVC animated:YES];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
    self.navigationController.navigationBar.tintColor = nil;
}

- (void)goWish {
    RecordTableViewController *recordTVC = [[RecordTableViewController alloc] init];
    [self.navigationController pushViewController:recordTVC animated:YES];
    [self.navigationController.navigationBar setBackgroundImage:nil forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:nil];
    self.navigationController.navigationBar.tintColor = nil;
}

- (void)startAnimation:(BOOL)animation {
    float duration = 0;
    
    if (animation) {
        duration = 0.5;
        UIBarButtonItem *endItem = [UIBarButtonItem createBackImageItem];
        endItem.target = self;
        endItem.action = @selector(endAnimationWithBlock:);
        if (!self.menuItem) {
            self.menuItem = self.navigationItem.leftBarButtonItem;
        }
        self.navigationItem.leftBarButtonItem = endItem;
    } else {
        if (!self.menuItem) {
            self.menuItem = self.navigationItem.leftBarButtonItem;
        }
        self.navigationItem.leftBarButtonItem = nil;
        
        self.lifeTimeButton.alpha = 0;
        
        if (!self.chooseT) {
            _chooseT = [UIButton buttonWithType:UIButtonTypeSystem];
            _chooseT.frame = CGRectMake(kScreenWidth / 2 - 130, kScreenHeight - 90 - 64, self.lifeTimeButton.width, 30);
            [_chooseT setTitle:@"选择年龄" forState:UIControlStateNormal];
            [_chooseT setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            _chooseT.layer.cornerRadius = 15;
            _chooseT.layer.borderColor = [UIColor lightGrayColor].CGColor;
            _chooseT.layer.borderWidth = 1;
            _chooseT.tag = 4444;
            [_chooseT addTarget:self action:@selector(lifeTimeAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:_chooseT];
        } else {
            _chooseT.alpha = 1;
        }
        
        if (!self.chooseF) {
            _chooseF = [UIButton buttonWithType:UIButtonTypeSystem];
            _chooseF.frame = CGRectMake(kScreenWidth / 2 + 10, kScreenHeight - 90 - 64, self.lifeTimeButton.width, 30);
            [_chooseF setTitle:@"拒绝猜测" forState:UIControlStateNormal];
            [_chooseF setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            _chooseF.layer.cornerRadius = 15;
            _chooseF.layer.borderColor = [UIColor lightGrayColor].CGColor;
            _chooseF.layer.borderWidth = 1;
            _chooseF.tag = 3333;
            [_chooseF addTarget:self action:@selector(lifeTimeAction:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:_chooseF];
        } else {
            _chooseF.alpha = 1;
        }
    }
    
    [UIView animateWithDuration:duration animations:^{
        self.stackViewOne.alpha = 0;
        self.stackViewTwo.alpha = 0;
        self.timeLabel.alpha = 0;
        self.aLabel.alpha = 0;
        self.shareButton.alpha = 0;
        self.navigationItem.rightBarButtonItems = nil;
        
        if (!self.clockView) {
            _clockView = [[ClockView alloc] initWithFrame:self.deadImageVIew.bounds hour:0 minute:0 second:-1 autoRun:NO];
            [self.clockView changeColor];
            self.clockView.center = CGPointMake(self.deadImageVIew.width / 2, self.deadImageVIew.height / 2);
            [self.deadImageVIew addSubview:self.clockView];
        }
        self.clockView.transform = CGAffineTransformMakeTranslation(0, 30);
        
        [self.lifeTimeButton setTitle:@"选择年龄" forState:UIControlStateNormal];
        self.lifeTimeButton.tag = 4444;
        self.lifeTimeButton.transform = CGAffineTransformMakeTranslation(0, -30);
        
        if (self.bLabel) {
            self.bLabel.alpha = 1;
        } else {
            self.bLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,self.deadImageVIew.y +  30 + self.deadImageVIew.height + 20 + 21 + 10, kScreenWidth - 40, 21)];
            self.bLabel.textAlignment = NSTextAlignmentCenter;
            self.bLabel.text = @"你猜测自己能活多少岁";
            self.bLabel.textColor = [UIColor whiteColor];
            [self.view addSubview:self.bLabel];
        }
    }];
}

- (void)endAnimationWithBlock:(id)block {
    [UIView animateWithDuration:0.5 animations:^{
        self.chooseT.alpha = 0;
        self.chooseF.alpha = 0;
        self.lifeTimeButton.alpha = 1;
        self.stackViewOne.alpha = 1;
        self.stackViewTwo.alpha = 1;
        self.timeLabel.alpha = 1;
        self.aLabel.alpha = 1;
        self.shareButton.alpha = 1;
        self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:self.wishItem, self.headItem, nil];
        self.navigationItem.leftBarButtonItem = self.menuItem;
        
        self.clockView.transform = CGAffineTransformMakeTranslation(0, 0);
        
        [self.lifeTimeButton setTitle:@"生之时" forState:UIControlStateNormal];
        self.lifeTimeButton.tag = 3333;
        self.lifeTimeButton.transform = CGAffineTransformMakeTranslation(0, 0);
        
        self.bLabel.alpha = 0;
    } completion:^(BOOL finished) {
        if (block && ![block isMemberOfClass:[UIBarButtonItem class]]) {
            ((void(^)())block)();
        }
        
    }];
}

- (void)createPicker {
    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    if (!self.backgroundView) {
        _backgroundView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _backgroundView.backgroundColor = [UIColor blackColor];
        [delegate.window addSubview:_backgroundView];
        self.backgroundView.alpha = 0.5;
        self.backgroundView.hidden = YES;
    }
    
    if (!self.pickerView) {
        _pickerView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, 250)];
        _pickerView.backgroundColor = [UIColor whiteColor];
        [delegate.window addSubview:_pickerView];
        
        UIButton *cancel = [UIButton buttonWithType:UIButtonTypeSystem];
        cancel.frame = CGRectMake(0, 0, 40, 30);
        [cancel setTitle:@"取消" forState:UIControlStateNormal];
        cancel.tintColor = [UIColor blackColor];
        [cancel addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
        [_pickerView addSubview:cancel];
        
        UIButton *confirm = [UIButton buttonWithType:UIButtonTypeSystem];
        confirm.frame = CGRectMake(kScreenWidth - 40, 0, 40, 30);
        [confirm setTitle:@"完成" forState:UIControlStateNormal];
        confirm.tintColor = [UIColor blackColor];
        [confirm addTarget:self action:@selector(confirm) forControlEvents:UIControlEventTouchUpInside];
        [_pickerView addSubview:confirm];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, kScreenWidth - 80, 30)];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"选择死亡年龄";
        [_pickerView addSubview:label];
        
        if (!self.picker) {
            _picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 30, kScreenWidth, 220)];
            _picker.delegate = self;
            _picker.dataSource = self;
            [_pickerView addSubview:_picker];
            [_picker selectRow:100 - self.age - 1 inComponent:0 animated:NO];
        }
    }

}

- (void)showPicker {
    self.backgroundView.hidden = NO;
    [UIView animateWithDuration:0.3 animations:^{
        self.pickerView.transform = CGAffineTransformMakeTranslation(0, -250);
    }];
}

- (void)confirm {
    [[YYCoreDataHandler sharedCoreDataHandler] updateObjectByKey:[[NSUserDefaults standardUserDefaults] objectForKey:@"currentUser"] withDictionary:[NSDictionary dictionaryWithObject:@([self.picker selectedRowInComponent:0] + 1 + self.age) forKey:@"maxAge"]];
    
    [self cancel];
    [self endAnimationWithBlock:nil];
    [self showData];
}

- (void)cancel {
    self.backgroundView.hidden = YES;
    [UIView animateWithDuration:0.3 animations:^{
        self.pickerView.transform = CGAffineTransformMakeTranslation(0, 0);
    }];
}

- (IBAction)share:(UIButton *)sender {
    NSLog(@"share");
}

- (IBAction)lifeTimeAction:(UIButton *)sender {
    if (sender.tag == 3333) {
        self.lifeBlock();
    } else if (sender.tag == 4444) {
        [self createPicker];
        [self showPicker];
    }
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return 100 - _age;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return [NSString stringWithFormat:@"%ld", row + 1 + self.age];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
